//
//  LanguageManager.m
//  YMDrawingBoard
//
//  Created by 刘家俊 on 2020/12/3.
//  Copyright © 2020 余默. All rights reserved.
//

#import "LanguageManager.h"

@interface LanguageManager ()

@property (nonatomic,strong) NSDictionary<NSString *,NSString *> *languageBundleMap;
@property (nonatomic,copy) NSString *preLanguageId;

@end

@implementation LanguageManager


#define     XYUserDefaults           [NSUserDefaults standardUserDefaults]
#define languageIdKey @"languageIdKey"

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self initLanguageBundleMap];
        NSString *cacheId = [XYUserDefaults objectForKey:languageIdKey]; //这里是优先获取设置的语言，如果没有设置，则获取系统的语言
        if (cacheId) {
            self.preLanguageId = cacheId;
        } else {
            self.preLanguageId = [self getPreferredLanguage];
        }
    }
    return self;
}

//获取系统当前语言
- (NSString*)getPreferredLanguage {

    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];

    NSArray * allLanguages = [defaults objectForKey:@"AppleLanguages"];

    NSString * preferredLang = [allLanguages objectAtIndex:0];

    return preferredLang;
}

- (void)initLanguageBundleMap {
    _languageBundleMap = @{
                           @"zh":@"zh-Hans", // 简体中文
                           @"en":@"en", // 英语
                           };
}

+ (instancetype)shareManager {
    static dispatch_once_t onceToken;
    static LanguageManager *instance = nil;
    dispatch_once(&onceToken, ^{
        instance = [[LanguageManager alloc] init];
    });
    return instance;
}

//当前语言id
- (NSString *)ym_currentLanguageId {
    return self.preLanguageId;
}

/**
 获取国际化文字

 @param string 对应的中文字符串
 @return 国际化字符串
 */
- (NSString *)ym_languageInternation:(NSString *)string {
    NSString *languagePath = [[NSBundle mainBundle] pathForResource:self.languageBundleMap[self.preLanguageId] ofType:@"lproj"];
    NSString *str = [[NSBundle bundleWithPath:languagePath] localizedStringForKey:string value:nil table:nil];
    return str;
}

/** 更换语言   */
- (void)ym_changeLanguage:(NSString *)languageId {
    
    if ([languageId isEqualToString:self.preLanguageId]) {
        return;
    }
    
    self.preLanguageId = languageId;
    
    //保存在本地id在本地
    [XYUserDefaults setObject:languageId forKey:languageIdKey];
    [XYUserDefaults synchronize];
    
    //改变语言之后，通知app
//    [[NSNotificationCenter defaultCenter] postNotificationName:languageIdKey object:nil];
    
}

@end
